package com.liesheng.haylou.ui.device.vm;

import android.graphics.Typeface;
import android.view.View;

import androidx.databinding.ObservableInt;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.liesheng.daemonlib.LogUtil;
import com.liesheng.haylou.R;
import com.liesheng.haylou.app.HyApplication;
import com.liesheng.haylou.base.BaseVm;
import com.liesheng.haylou.bluetooth.BleGattConnectListener;
import com.liesheng.haylou.bluetooth.BleManager;
import com.liesheng.haylou.bluetooth.BleUUIDs;
import com.liesheng.haylou.bluetooth.ScanRecordUtil;
import com.liesheng.haylou.common.recycleView.CommonAdapter;
import com.liesheng.haylou.databinding.ItemBleEqBinding;
import com.liesheng.haylou.db.DBManager;
import com.liesheng.haylou.event.AddBoundDeviceEvent;
import com.liesheng.haylou.event.DeviceBatteryChangeEvent;
import com.liesheng.haylou.ui.device.DeviceDetailActivity;
import com.liesheng.haylou.ui.setting.SetttingEqActivity;
import com.liesheng.haylou.utils.sp.SpKey;
import com.liesheng.haylou.utils.sp.SpUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Date:2019/12/4
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description:
 */
public class DeviceDetailVm extends BaseVm<DeviceDetailActivity> implements BleGattConnectListener {

    public ObservableInt leftBattery = new ObservableInt();//电量低要显示黄色
    public ObservableInt rightBattery = new ObservableInt();//电量低要显示黄色
    public ObservableInt boxBattery = new ObservableInt();//电量低要显示黄色

    List<String> datas = new ArrayList<>();

    private int selectedP = 0;

    BleManager bleManager;

    boolean isConnect = false;

    String[] eq_items;
    String[] eq_values;

    private List<String> headset_contrals;

    String version = "";

    public DeviceDetailVm(DeviceDetailActivity mActivity) {
        super(mActivity);
    }

    public void init() {
        mActivity.mBinding.setVm(this);

        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mActivity.mBinding.mRecyclerView.setLayoutManager(manager);
        mActivity.mBinding.mRecyclerView.setAdapter(adapter);

        eq_items = mActivity.getResources().getStringArray(R.array.eq_items);
        eq_values = mActivity.getResources().getStringArray(R.array.eq_items_values);
        datas.clear();
        datas.addAll(Arrays.asList(eq_items));
        adapter.notifyDataSetChanged();

        headset_contrals = Arrays.asList(mActivity.getResources().getStringArray(R.array.headset_contral));

        getLocation();
    }


    public void connentDevice() {
        if (!mActivity.isBluetoothOpen())
            return;
        mActivity.showLoadingDialog("连接中...");
        mActivity.mBinding.btUnlink.setEnabled(false);
        if (bleManager == null)
            bleManager = BleManager.getInstance();

        if (bleManager.getBluetoothGatt(mActivity.getBoundedDevice().getAddress()) != null) {//蓝牙已经连接
            bleManager.connect(mActivity.getBoundedDevice().getAddress(), this);
        } else if (mActivity.getBluetoothDevice() != null) {//已扫描到了蓝牙 但是还未连接
            bleManager.connect(mActivity.getBoundedDevice().getAddress(), mActivity.getBluetoothDevice(), this);
        } else {//蓝牙未连接 且 还未扫描到
            //扫描蓝牙--连接
            mActivity.dismissLoadingDialog();
        }

    }


    private void read(final String bleAddress, final String characteristicUuid) {
        Observable.timer(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        bleManager.read(bleAddress, characteristicUuid);
                    }
                });
    }

    CommonAdapter adapter = new CommonAdapter<String, ItemBleEqBinding>(mActivity, datas, R.layout.item_ble_eq) {

        @Override
        public void contentConvert(ItemBleEqBinding binding, final String eq, final int position) {
            binding.tvEq.setText(eq.split("-")[1]);
            binding.tvEq.setBackgroundResource(position == selectedP ? R.drawable.btn_yuan1 : R.drawable.btn_yuann_selector_n);
            binding.tvEq.setTypeface(Typeface.defaultFromStyle(position == selectedP ? Typeface.BOLD : Typeface.NORMAL));//加粗
            binding.tvEq.setTextColor(mActivity.getResources().getColor(position == selectedP ? R.color.color_FE622D : R.color.color_333));
            binding.getRoot().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (!isConnect) return;

                    if (position == 1) {//自定义
                        SetttingEqActivity.startBy(mActivity, mActivity.getBoundedDevice().getAddress());
                    } else {
                        SpUtil.put(SpKey.EQ_POSITION, position);
                        selectedP = position;
                        notifyDataSetChanged();
                        SetttingEqActivity.startBy(mActivity, mActivity.getBoundedDevice().getAddress());
                        String value = "";
                        for (String s : eq_values) {
                            if (s.contains(eq.split("-")[0])) {
                                value = s.replaceAll("-", "");
                                break;
                            }
                        }
                        bleManager.write(mActivity.getBoundedDevice().getAddress(), BleUUIDs.CHAR_EQ, value);
                        LogUtil.d("DeviceDetailVm--onWrite", "写入:" + value);
                    }


                }
            });

        }
    };


    @Override
    public void onConnect() {
        mActivity.dismissLoadingDialog();
        getLocation();
        setConnect(true);
        //连接上之后读取数据
        bleManager.setNotify(mActivity.getBoundedDevice().getAddress(), BleUUIDs.CHAR_STATUS);
        read(mActivity.getBoundedDevice().getAddress(), BleUUIDs.CHAR_LANGUAGE);
        if (DBManager.getInstance().getDaoSession().getBoundedDeviceDao().insertOrReplace(mActivity.getBoundedDevice()) > 0) {
            EventBus.getDefault().post(new AddBoundDeviceEvent(mActivity.getBoundedDevice()));
        }
    }

    @Override
    public void onDisConnect() {
        mActivity.dismissLoadingDialog();
        setConnect(false);
    }

    @Override
    public void onRead(int status, String uuid, String hexResult) {
        LogUtil.d("DeviceDetailVm--onRead", Thread.currentThread().getName() + "---" + hexResult + "---" + uuid);
        if (status == 0) {
            switch (uuid.toLowerCase()) {
                case BleUUIDs.CHAR_LANGUAGE:
                    read(mActivity.getBoundedDevice().getAddress(), BleUUIDs.CHAR_STATUS);
                    break;
                case BleUUIDs.CHAR_STATUS:
                    read(mActivity.getBoundedDevice().getAddress(), BleUUIDs.CHAR_VERSION);

                    int[] batteries = new int[3];
                    int[] charging = new int[3];

                    List<int[]> list = ScanRecordUtil.getBattey(hexResult);

                    mActivity.mBinding.tvBox.setText(mActivity.getStr(R.string.battery_box, list.get(0)[1]));
                    mActivity.mBinding.chargeBox.setVisibility(list.get(0)[0] == 1 ? View.VISIBLE : View.INVISIBLE);
                    if (list.get(0)[1] <= 0)
                        mActivity.mBinding.tvBox.setText(mActivity.getStr(R.string.battery_box_none));
                    boxBattery.set(list.get(0)[1]);
                    charging[0] = list.get(0)[0];
                    batteries[0] = list.get(0)[1];

                    mActivity.mBinding.tvLeft.setText(mActivity.getStr(R.string.battery_left, list.get(1)[1]));
                    mActivity.mBinding.chargeLeft.setVisibility(list.get(1)[0] == 1 ? View.VISIBLE : View.INVISIBLE);
                    leftBattery.set(list.get(1)[1]);
                    charging[1] = list.get(1)[0];
                    batteries[1] = list.get(1)[1];

                    mActivity.mBinding.tvRight.setText(mActivity.getStr(R.string.battery_right, list.get(2)[1]));
                    mActivity.mBinding.chargeRight.setVisibility(list.get(2)[0] == 1 ? View.VISIBLE : View.INVISIBLE);
                    rightBattery.set(list.get(2)[1]);
                    charging[2] = list.get(2)[0];
                    batteries[2] = list.get(2)[1];

                    mActivity.getBoundedDevice().setBatteries(batteries);
                    mActivity.getBoundedDevice().setCharging(charging);
                    EventBus.getDefault().post(new DeviceBatteryChangeEvent(mActivity.getBoundedDevice()));

                    break;
                case BleUUIDs.CHAR_VERSION:
                    read(mActivity.getBoundedDevice().getAddress(), BleUUIDs.CHAR_LEFT_CLICK_DOUBLE);
                    version = ScanRecordUtil.getVersion(hexResult);
                    mActivity.mBinding.tvVersion.setText(version);
                    break;
                case BleUUIDs.CHAR_LEFT_CLICK_DOUBLE://左耳机双击
                    read(mActivity.getBoundedDevice().getAddress(), BleUUIDs.CHAR_RIGHT_CLICK_DOUBLE);
                    mActivity.mBinding.tvDoubleLeft.setText(getHeadsetContral(hexResult));
                    break;
                case BleUUIDs.CHAR_RIGHT_CLICK_DOUBLE://左耳机双击
                    read(mActivity.getBoundedDevice().getAddress(), BleUUIDs.CHAR_RIGHT_CLICK_THREE);
                    mActivity.mBinding.tvDoubleRight.setText(getHeadsetContral(hexResult));
                    break;
                case BleUUIDs.CHAR_RIGHT_CLICK_THREE://三击
                    read(mActivity.getBoundedDevice().getAddress(), BleUUIDs.CHAR_EQ);
                    mActivity.mBinding.tvThreeKey.setText(getHeadsetContral(hexResult));
                    break;
                case BleUUIDs.CHAR_EQ:

                    String eq = ScanRecordUtil.getEQType(hexResult);
                    for (int i = 0; i < eq_items.length; i++) {
                        if (eq_items[i].contains(eq)) {
                            selectedP = i;
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
            }
        }
    }

    private String getHeadsetContral(String hexResult) {
        String c = hexResult;
        for (String s : headset_contrals) {
            if (s.contains(hexResult)) {
                c = s;
                break;
            }
        }
        return c;
    }

    //设备耳机按键控制
    public void showContralDialog(final int type, String selectItem) {
        //条件选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                String address = mActivity.getBoundedDevice().getAddress();
                String value = headset_contrals.get(options1).split("-")[0];
                String uuid = BleUUIDs.CHAR_LEFT_CLICK_DOUBLE;
                switch (type) {
                    case 0://左耳机双击
                        mActivity.mBinding.tvDoubleLeft.setText(headset_contrals.get(options1));
                        uuid = BleUUIDs.CHAR_LEFT_CLICK_DOUBLE;
                        break;
                    case 1://右耳机双击
                        mActivity.mBinding.tvDoubleRight.setText(headset_contrals.get(options1));
                        uuid = BleUUIDs.CHAR_RIGHT_CLICK_DOUBLE;
                        break;
                    case 2://三击
                        mActivity.mBinding.tvThreeKey.setText(headset_contrals.get(options1));
                        uuid = BleUUIDs.CHAR_RIGHT_CLICK_THREE;
                        break;
                }
                bleManager.write(address, uuid, value);
            }
        }).setTitleText("耳机控制")
                .setTitleBgColor(mActivity.getResources().getColor(R.color.white))
                .setCancelColor(mActivity.getResources().getColor(R.color.color_8A8A8D)).build();
        pvOptions.setPicker(headset_contrals);
        for (int i = 0; i < headset_contrals.size(); i++) {
            if (headset_contrals.get(i).contains(selectItem)) {
                pvOptions.setSelectOptions(i);
                break;
            }
        }
        pvOptions.show();

    }


    @Override
    public void onNotify(String uuid, String hexResult) {
        LogUtil.d("DeviceDetailVm--onNotify", hexResult + "---" + uuid);
    }

    @Override
    public void onWrite(int status, String uuid) {
        if (status == 0) {
            mActivity.showToast("设置成功");

        } else {
            mActivity.showToast("设置失败,错误码为:" + status);
        }
    }

    public void setConnect(boolean connect) {

        //如果是由连接状态转为断开的,则自动退出页面
        if (isConnect && !connect) {
            mActivity.finish();
        }

        isConnect = connect;
        mActivity.mBinding.btUnlink.setText(isConnect ? R.string.ble_disconnect : R.string.ble_connect);
        mActivity.mBinding.btUnlink.setEnabled(true);
        if (!isConnect) {
            mActivity.showToast(R.string.ble_connected);
        }
    }

    AMapLocationClient mLocationClient;

    private void getLocation() {
        mLocationClient = new AMapLocationClient(HyApplication.mApp);
        //设置定位回调监听
        mLocationClient.setLocationListener(locationListener);
        mLocationClient.startLocation();
    }

    double latitude, longitude;

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                latitude = aMapLocation.getLatitude();
                longitude = aMapLocation.getLongitude();
                String location = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict();
                mActivity.getBoundedDevice().setLatitude(latitude);
                mActivity.getBoundedDevice().setLongitude(longitude);
                mActivity.getBoundedDevice().addLocateion(location);

                DBManager.getInstance().getDaoSession().getBoundedDeviceDao().insertOrReplace(mActivity.getBoundedDevice());
            }
        }
    };

    public void changeConnect() {
        if (isConnect) {
            bleManager.closeConn(mActivity.getBoundedDevice().getAddress());
            setConnect(false);
        } else {
            connentDevice();
        }
    }

    public boolean isConnect() {
        return isConnect;
    }

    public String getVersion() {
        return version;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        BleManager.getInstance().closeConn(mActivity.getBoundedDevice().getAddress());
    }

    public void notifiAdapter() {
        if (SpUtil.getInt(SpKey.EQ_POSITION, -1) > 0) {
            selectedP = SpUtil.getInt(SpKey.EQ_POSITION, 2);
            adapter.notifyDataSetChanged();
        }
    }
}
